package cn.hit.edu.switter.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.hit.edu.switter.DatabaseHelper;

/**
 * Servlet implementation class Validation
 */
@WebServlet("/Validation")
public class Validation extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public Validation() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		String email = request.getParameter("loginname");
		String pass  = request.getParameter("loginpass");
		//System.out.println(email + "\n" + pass);
		
		DatabaseHelper db = new DatabaseHelper();
		int userId = db.verifyAccount(email, pass);
		
		System.out.println(userId);
		db.closeConnection();
		if (userId == -1) {
			response.sendRedirect("/Switter_beta/login.html");
		} else {
			//System.out.println("fuck");
			HttpSession session = request.getSession();
			session.setAttribute("UserId", new Integer(userId));
			/*PrintWriter out = response.getWriter();
			out.println("<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN http://www.w3.org/TR/html4/loose.dtd>"
					+ "<script>alert(\"Login Success\");</script>");*/
			response.sendRedirect("/Switter_beta/index.jsp");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
